<?php
class FriendAction extends Action {

	const FRIEND_BLACK_LIST = 0; // 黑名单
	const FRIEND_KNOW_ONLY = 1; // 只认识
	const FRIEND_PLAY = 2; // 一起玩的
	const FRIEND_GOOD = 3; // 好朋友

	private $require_authorization;
	
	public function _initialize() {
		$this->require_authorization = false;
	}
	
	public function index() {
		$users = M('user')->field('`uid`,`email`,`uname`')->findAll();
		$this->assign('users', $users);
//		dump($users);
		
		$friends = model('Friend')->getFriendList($this->mid, self::FRIEND_KNOW_ONLY );
		$this->assign('friends_known', $friends);

		$friends = model('Friend')->getFriendList($this->mid, self::FRIEND_PLAY );
		$this->assign('friends_play', $friends);

		$friends = model('Friend')->getFriendList($this->mid, self::FRIEND_GOOD );
		$this->assign('friends_good', $friends);
		
		//$fuids  = getSubByKey($friend['data'], 'friend_uid');
//		dump($fuids);
		//$group  = model('Friend')->getGroupOfFriend($this->mid, $fuids);
		//$this->assign('group', $group);
//		dump($group);
		
		//$groups = model('Friend')->getGroupList($this->mid, true);
		//$this->assign('groups', $groups);
//		dump($groups);

//		relative
		$maybeknown = model('Friend')->getRelatedUsers($this->mid, 50);
		$this->assign('maybeknown', $maybeknown);

		$this->display();
	}
	
	public function doAddFriend() {
		//准备参数，合法性检验
		$gid  = explode( ',', rtrim(t($_REQUEST['gid']), ',') );
		$fuid = intval($_REQUEST['fuid']);
		if ($fuid <= 0 || $this->mid == $fuid) {
			echo 0; 
			return;
		}
		
		foreach ($gid as $k => $v) {
			if ($v <= 0) {
				unset($gid[$k]);
				continue;
			}
		}
		$gid  = empty($gid) ? 0 : $gid;
		
		//已经是好友
		if ( model('Friend')->isFriends($this->mid, $fuid) ) {
			echo -1;
			return ;
		}
		
		//添加好友
		$res = model('Friend')->addFriend($this->mid, $fuid, $gid, $this->require_authorization, t($_REQUEST['message']));

		if ($res) {
			//发送通知
			//发送动态
			//添加积分
			echo 1;
		}else {
			echo 0;
		}
	}
	
	public function selectFriendGroup() {
		$groups = model('Friend')->getGroupList($this->mid);
		
		$this->assign('groups', $groups);
		$this->assign('fuid', intval($_GET['fuid']));
		$this->assign('require_authorization', $this->require_authorization ? 1 : 0);
		$this->display();
	}
	
	public function setFriendGroup() 
	{
		//uid friend_uid friend_uname friend_group_id status 
		$data['friend_group_id'] = $_GET['gid'];
		$data['status'] = 1;
		$res = M('friend_group_link')->where("uid={$this->mid} AND friend_uid={$_GET['fuid']}" )->data($data)->save();
		if ($res) {
			echo 1;
		}else {
			//var_dump(M('friend_group_link')->getDbError());
			echo 0;
		}		
	}
	
	public function info()
	{
		$this->display();
	}
	
	public function deleteFriend()
	{
		if (model('friend')->deleteFriend($this->mid, $_GET['fuid'])) {
			echo 1;
		} else {
			echo 0;
		}
	}
	
	public function card()
	{
		W('FriendCard', array('mid' => $this->mid));
	}
}